/*!
 * Copyright (c) 2010 Jacob Essex
 *
 * Dual licenced under MIT or GPL 3 licneces
 * 
 * See the GPL3 or MIT files in the main directory for details
 */

/**
 * this expects html to be formatted in a spesific way and the html to be rendered
 */
require.def('pages/control', ['lib/hashstring', 'lib/template', 'templates/qsum', 'lib/jquery'],
function(Hashstring, Template, QuestionSummary){
    var obj = {};


    obj.DefaultContentManager=function(prefix){
        this.setPrefix = function(p){
            prefix = p;
        }
        this.showError = function(msg){
            $('#' + prefix + '-content').append('<div class="supernova" style="font-size: 130%;padding:20px">Error:' + msg + '</div>');
        }
        this.setContent = function(html){
            $('#' + prefix + '-content').html(html);
        }
        this.setLoadingInformation = function(html){
            $('#' + prefix + '-info').html(html);
        }
    };
    obj.QuestionList=function(){
        var that = this;
        var prefix = '';

        this.setPrefix = function(p){
            prefix = p;
        }

        this.setContent = function(html){
            $('#' + prefix + '-content').html(html);
        }

        var toText = function(html){
            return $('<div>'+html+'</div>').text();
        }
                  
        this.addQuestion = function(question){
            require(['formatter/rep', 'formatter/votecount'], 
            function(Rep, VoteCount){
                var q = question;
                var o = q.owner;
                //the two toText() calls are required as if the user writes html in their
                //post in a code block it seems to be converted to html. 
                var body = toText(toText(q.body)).substr(0,200);
                var data = {
                    title:q.title,
                    questionId:q.question_id,
                    views:VoteCount.format(q.view_count),
                    voteCount:VoteCount.format(q.score),
                    excerpt:body,
                    userName:o.display_name,
                    userId:o.user_id,
                    userRep:Rep.format(o.reputation),
                    emailHash:o.email_hash,
                    answerCount:q.answer_count,
                    tags:q.tags
                }

                var html = Template.tmpl(QuestionSummary.text, data);

                $('#' + prefix + '-content').append(html);
            });
        }
        
    };
    obj.QuestionList.prototype = new obj.DefaultContentManager();

    obj.PageController=function(prefix){
        var that = this;
        var hs = Hashstring;
        var offset = hs.get('offset', 0);
        var pageLoader;
        var contentMgr = new obj.DefaultContentManager(prefix);

        var pageOffsets = [0];
        var currentPageNum = 0;

        this.getContentMgr = function(){
            return contentMgr;
        }
        this.setContentMgr = function(cm){
            cm.setPrefix(prefix);
            cm.__proto__.setPrefix(prefix);
            contentMgr = cm;
        }
        
        
        var updatePageSizeUi = function(){
            $('#' + prefix + '-sizer' ).removeClass('current');
            $('#' + prefix + '-sizer-' + that.getPageSize()).addClass('current');
        }

        this.getPageSize = function(){
            var ps = localStorage.getItem('relevant.pageSize') ;
            if ( ps == null ){
                ps = hs.get('page', '10');
            }
            //todo move to array
            if ( ps != 10 && ps != 20 && ps != 30 && ps != 50 ){
                ps = 30;
            }
            return ps;
        }

        this.setPageSize = function(ps){
            if ( ps != 10 && ps != 20 && ps != 30 && ps != 50 ){
                ps = 10;
            }
            hs.set('page', ps);
            localStorage.setItem('relevant.pageSize', ps);
            updatePageSizeUi();

            //as setting the page size messes up our offsets, we need to reset eveything
            pageOffsets = [0];
            currentPageNum = 0;
            that.load();
            
        }

        $('#' + prefix + '-sizer a').click(function(){
            that.setPageSize($(this).html());
        });
        updatePageSizeUi();


        //seperate function so we can unbind and then rebind the function to stop it being called
        //while it is loading
        var nextFunc = function(){
            setLoading();
            scroll(0,0)

            var t = $(this);
            currentPageNum++;
            pageLoader.call(that, pageOffsets[currentPageNum], that.getPageSize(), function(newOffset){
                pageOffsets[currentPageNum+1] = newOffset;
                unsetLoading();
            });
        };
        var previousFunc = function(){
            setLoading();
            scroll(0,0)

            var t = $(this);
            if ( currentPageNum > 0 ){
                currentPageNum--;
                pageLoader.call(that, pageOffsets[currentPageNum], that.getPageSize(), function(){
                    unsetLoading();
                });
            }
        }


        this.disablePager = function(){
            $('#' + prefix + '-pager-next').unbind();
            $('#' + prefix + '-pager-previous').unbind();

            $('#' + prefix + '-pager a span').attr('style', 'opacity:0.4');
        }
        this.enablePager = function(){
            $('#' + prefix + '-pager a span').attr('style', '');

            //unbind all previous events as the pageloader can be set again
            $('#' + prefix + '-pager-next').unbind().click(nextFunc);
            $('#' + prefix + '-pager-previous').unbind().click(previousFunc);
        }

        var setLoading = function(){
            $('#' + prefix + '-info').html('Loading...');
            that.disablePager();
        }

        var unsetLoading = function(){
            $('#' + prefix + '-info').html('');
            that.enablePager();

        }


        this.setPageLoader = function(callback){
            pageLoader = callback;
            
            //set it to the sate where it is ready to be used
            unsetLoading();

        
        }

        this.load = function(){
            setLoading();
            pageLoader.call(that,pageOffsets[currentPageNum], that.getPageSize(), function(newOffset){
                pageOffsets[currentPageNum+1] = newOffset;

                unsetLoading();
            });

        }

    }

    return obj;

});
